import {
	jumpPage
} from "../index";

import {decryptData, encryptData} from '../encrypt';
// 请求计数器（用于处理并发请求）
let requestCount = 0;

// 显示加载动画
const showLoading = () => {
	if (requestCount === 0) {
		uni.showLoading({
			title: '加载中',
			mask: true
		});
	}
	requestCount++;
};

// 隐藏加载动画
const hideLoading = () => {
	requestCount--;
	if (requestCount === 0) {
		uni.hideLoading();
	}
};

// 处理响应错误
const handleResponseError = (error, reject) => {
	console.error("请求错误:", error);
	let errorMsg = "网络异常,请稍后重试!";

	if (error.errMsg) {
		if (error.errMsg.includes("timeout")) {
			errorMsg = "请求超时，请检查网络连接";
		} else if (error.errMsg.includes("fail")) {
			errorMsg = "网络连接失败";
		}
	}

	uni.showToast({
		icon: "none",
		duration: 3000,
		title: errorMsg
	});

	reject(error);
};

// 基础请求方法
let request = ({
	url,
	method = 'GET',
	data = {},
	header = {},
	showLoad = true,
	timeout = 30000
}) => {
	return new Promise((resolve, reject) => {
		// 显示加载动画
		if (showLoad) showLoading();

		try {
			// 获取服务器配置
			const server = uni.getStorageSync("server") || {};
			let baseUrl = server.ip ? `http://${server.ip}:${server.port || '80'}` : '';

			// 处理URL
			if (!url.startsWith("http") && !url.startsWith("/")) {
				baseUrl = baseUrl + "/";
			}

			// 获取Token
			const token = uni.getStorageSync('token');

			// 设置默认请求头
			const defaultHeader = {
				'Content-Type': 'application/json;charset=utf-8',
			};

			// 添加Token
			if (token) {
				defaultHeader['Authorization'] = 'Bearer ' + token;
			}

			// 合并请求头
			const finalHeader = {
				...defaultHeader,
				...header
			};

			// 发起请求
			uni.request({
				url: baseUrl + url,
				data,
				method,
				header: finalHeader,
				timeout,
				success(res) {
					try {
						const {
							code,
							msg,
							data: responseData
						} = res.data;

						// Token过期处理
						if (code === 30007) {
							uni.showToast({
								icon: "none",
								duration: 3000,
								title: "登录已过期，请重新登录"
							});
							jumpPage("/login/index");
							return reject(new Error(msg));
						}

						// 请求成功
						if (code === 0) {
							return resolve({
								data: responseData,
								msg: msg || '请求成功'
							});
						}

						// 其他错误
						uni.showToast({
							icon: "none",
							duration: 3000,
							title: msg || '请求失败'
						});
						return reject(new Error(msg || '请求失败'));
					} catch (parseError) {
						console.error("响应解析错误:", parseError);
						handleResponseError(new Error("响应数据解析失败"), reject);
					}
				},
				fail(error) {
					handleResponseError(error, reject);
				},
				complete() {
					if (showLoad) hideLoading();
				}
			});
		} catch (configError) {
			console.error("请求配置错误:", configError);
			handleResponseError(new Error("请求配置错误"), reject);
			if (showLoad) hideLoading();
		}
	});
};

// GET请求
export const get = (url = '', data = {}, config = {}) => request({
	url,
	method: "GET",
	data,
	...config
});

// POST请求
export const post = (url = '', data = {}, config = {}) => request({
	url,
	method: "POST",
	data,
	...config
});

export const postEncryptRequest = (url = '', data1 = {}, config = {}) => request({
	url,
	method: "POST",
	data: { encryptData: encryptData(data1) },
	...config
});

// PUT请求
export const put = (url = '', data = {}, config = {}) => request({
	url,
	method: "PUT",
	data,
	...config
});

// DELETE请求
export const del = (url = '', data = {}, config = {}) => request({
	url,
	method: "DELETE",
	data,
	...config
});

// 文件上传
export const upload = (url, filePath, name = 'file', formData = {}, config = {}) => {
	return new Promise((resolve, reject) => {
		showLoading();

		const server = uni.getStorageSync("server") || {};
		let baseUrl = server.ip ? `http://${server.ip}:${server.port || '80'}` : '';

		const token = uni.getStorageSync('token');
		const header = {
			'Authorization': token ? 'Bearer ' + token : ''
		};

		uni.uploadFile({
			url: baseUrl + url,
			filePath,
			name,
			formData,
			header,
			success(res) {
				try {
					const data = JSON.parse(res.data);
					if (data.code === 0) {
						resolve(data);
					} else {
						uni.showToast({
							icon: "none",
							title: data.msg || '上传失败'
						});
						reject(data);
					}
				} catch (e) {
					reject(new Error('上传响应解析失败'));
				}
			},
			fail(error) {
				handleResponseError(error, reject);
			},
			complete() {
				hideLoading();
			}
		});
	});
};